// dsp 业务上的共用方法。
define(function(require, exports){
	var util = require('util');

	/*
		实现数据的map方法.
	 */
	exports.map = function(arr, func) {
		if(arr && arr.length) {
			for(var i = 0; i < arr.length; i++) {
				arr[i] = func(arr[i]);
			}
		}

		return arr;
	};
	/**
	 * 获取字符串长度
	 * @return {Number} 返回字符串长度
	 */
	exports.byteLen = function(str){
		if(!str){
			return 0;
		}
		var result = 0;
		var len = str.length;
		for(var i=0; i<len; i++){
			result += str.charCodeAt(i) > 255 ? 2 : 1;
		}
		return result;
	};

	exports.filterMenu = function(m, app) {
		for(var i = 0; i < m.length; i++)
		{
			var menu = m[i];
			for(var j = menu.length -1; j >= 0; j--)
			{
				if(menu[j] && menu[j].navRight && !app.checkRight(menu[j].navRight))
				{
					menu.splice(j, 1);
				}
				else if(menu[j].items)
				{
					for(var k = menu[j].items.length -1; k >= 0; k--)
					{
						var sub = menu[j].items[k];
						if(sub && sub.navRight && !app.checkRight(sub.navRight))
						{
							menu[j].items.splice(k, 1);
						}
					}
				}
			}
		}
	};

	exports._convertArrayGroup = function(name, value, data, config){
		var res = [];
		util.each(data, function(group){
			var item = exports._convertArray(
				LANG(group.text),
				value,
				group.list,
				config
			);
			delete item.value;
			res.push(item);
		});
		return {'name':name, 'value':value, 'child':res, 'config':config};
	};

	//转换格式
	exports._convertArray = function(name, value, data, config){
		var res = [];
		util.each(data, function(item,key){
			var name, k;
			if(util.isString(item)) {
				name = LANG(item);
				k = value + ':' + key;
			}
			else {
				name = LANG(item.name);
				k = value + ':' + item.id;
			}
			res.push({
				'name': name,
				'value': k,
				'config': config
			});
		});
		return {'name':name, 'value':value, 'child':res, 'config': config};
	};

	// 该方法取得子数组的补集
	// 第一个参数为父数组，第二个参数为子数组
	// 考虑将该方法添加到util
	exports._complementArray = function(fatherArray, subArray) {
		return fatherArray.filter(function(e) {
			return subArray.indexOf(e) < 0;
		})
	};

	/**
	 * 键值对map转换为对象数组
	 * @param  {Object|Array} map             对象或数组
	 * @param  {Boolean}      sortByKey  可选 是否根据键值排序, 默认为false
	 * @param  {String}       keyField   可选 对象属性要转换为的属性名, 默认为id
	 * @param  {String}       valueField 可选 对象值要转换为的属性名, 默认为name
	 * @return {Array}                        对象数组
	 */
	exports._convertMapToItems = function(map, sortByKey, keyField, valueField) {
		var arr = [];

		keyField = keyField || 'id';
		valueField = valueField || 'name';

		util.each(map, function(value, key) {
			var item = {};
			item[keyField] = key;
			item[valueField] = LANG(value);
			arr.push(item);
		});

		if (!!sortByKey) {
			return arr.sort(function(a, b) {
				return a[keyField] - b[keyField] || 0;
			});
		}
	};

	exports.queryString = function(param)
	{
		var s = '';
		for(var prop in param)
		{
			if(param.hasOwnProperty(prop) && String(param[prop]))
			{
				s += '&' + prop + '=' + param[prop];
			}
		}

		return s;
	};

	exports.sizeFormat = function(value, fix)
	{
		if(value > 1024)
		{
			if(fix)
			{
				return (value/1024).toFixed(fix) + 'M';
			}
			else
			{
				return Math.round(value/1024) + 'M';
			}
		}
		else
		{
			return value.toFixed(fix || 2) + ' kb';
		}
	};

	// 函数截流
	exports.throttle = function(fn, delay, forceRunDelay){
		var timer = null;
		var start;
		return function()
		{
			var context = this, args = arguments, current = +new Date();
			clearTimeout(timer);
			if(!start)
			{
				start = current;
			}
			if(forceRunDelay && (current - start >= forceRunDelay))
			{
				fn.apply(context, args);
				start = current;
			}
			else
			{
				timer = setTimeout(function(){
					fn.apply(context, args);
				}, delay);
			}
		};
	};

	exports.format_date = function(val)
	{
		if(util.isNumber(+val) && val.toString().length==8){
			val = val.toString();
			val = val.substr(0,4) + '-' + val.substr(4,2) + '-' + val.substr(6,2);
		}

		return val
	};




	var week_map;
	exports.format_week = function(val)
	{
		if(!week_map)
		{
			week_map = {
				1: LANG('星期一')
				,2: LANG('星期二')
				,3: LANG('星期三')
				,4: LANG('星期四')
				,5: LANG('星期五')
				,6: LANG('星期六')
				,0: LANG('星期日')
			};
		}

		if(val !== undefined && week_map[val])
		{
			return week_map[val];
		}

		return LANG('未知');
	};

	exports.formatScheduleDay = function(hours)
	{
		var now = false;
		var str = '';
		if(hours && hours.length)
		{
			for(var i = 0; i < hours.length; i++)
			{
				if(now === false)
				{
					now = hours[i];
					str += ('0' + now).substr(-2) + ':00-';
				}
				else if(now + 1 == hours[i])
				{
					now ++;
				}
				else if(now + 1 !== hours[i])
				{
					now ++;
					str += ('0' + now).substr(-2) + ':00, ';
					now = hours[i];
					str += ('0' + now).substr(-2) + ':00-';
				}
			}

			if(now !== false)
			{
				now ++;
				str += ('0' + now).substr(-2) + ':00;';
			}
		}

		return str;
	};

	/*
		以换行来获取url, 适合多条http地址 记录
	 */
	exports.url_get = function (uri)
	{
		var str = uri.replace(/[\r\n]+/g, '\n').split('\n');
		var url = [];
		util.each(str, function(item){
			if(item)
			{
				url.push(item);
			}
		});

		return url;
	};

	/*
	 排除某些值
	 arr 比 exclude 多的值。
	 */
	exports.difference = function (arr, exclude) {
		var ret = [];
		if(Array.isArray(arr))
		{
			if(!Array.isArray(exclude))
			{
				exclude = [exclude];
			}

			arr.forEach(function(val) {
				var index = exclude.indexOf(val);
				if(!~index) {
					ret.push(val);
				}
			});
		}

		return ret;
	};

	exports.isDiff = function (arr1, arr2) {
		if(Array.isArray(arr1) && Array.isArray(arr2)) {
			if(arr1.length == arr2.length) {
				for(var item of arr1) {
					if(arr2.indexOf(item) == -1) {
						return false;
					}
				}
			}
		}

		return true;
	};

	function unique(arr) {
		return arr.filter(function(val, index) {
			return arr.lastIndexOf(val) === index;
		});
	}

	exports.unique = unique;

	/*
	 取交集并去从.
	 */
	function intersection(one , two) {
		var ret = [];
		if(Array.isArray(one) && Array.isArray(two)) {
			var first, second;
			// 小的做第一层循环
			if(one.length > two.length) {
				first = two;
				second = one;
			}
			else {
				first = one;
				second = two;
			}

			first.forEach(function(val) {
				if(second.indexOf(val) !== -1) {
					ret.push(val);
				}
			});

			return unique(ret);
		}

		return [];
	}

	exports.intersection = intersection;

});
